package com.whiteape.book.utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.whiteape.book.WaApp;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.DownloadTaskBean;
import com.whiteape.book.model.dto.MediaRecordBean;
import com.whiteape.book.model.gen.CollectionMediaBeanDao;
import com.whiteape.book.model.gen.DaoMaster;
import com.whiteape.book.model.gen.DaoSession;
import com.whiteape.book.model.gen.DownloadTaskBeanDao;
import com.whiteape.book.model.gen.MediaRecordBeanDao;
import com.whiteape.book.model.gen.SiteSourceBeanDao;
import com.whiteape.book.model.gen.SiteSourceCategoryBeanDao;

import org.greenrobot.greendao.database.Database;


/**
 * Created by newbiechen on 17-4-26.
 */

public class DaoDbHelper {
    private static final String DB_NAME = "wa_db";

    private static volatile DaoDbHelper sInstance;
    private SQLiteDatabase mDb;
    private DaoMaster mDaoMaster;
    private DaoSession mSession;

    private DaoDbHelper(){
        //封装数据库的创建、更新、删除
        DaoMaster.OpenHelper openHelper = new MyOpenHelper(WaApp.getInstance().getApplicationContext(),DB_NAME,null);
        //获取数据库
        mDb = openHelper.getWritableDatabase();
        //封装数据库中表的创建、更新、删除
        mDaoMaster = new DaoMaster(mDb);  //合起来就是对数据库的操作
        //对表操作的对象。
        mSession = mDaoMaster.newSession(); //可以认为是对数据的操作
    }


    public static DaoDbHelper getInstance(){
        if (sInstance == null){
            synchronized (DaoDbHelper.class){
                if (sInstance == null){
                    sInstance = new DaoDbHelper();
                }
            }
        }
        return sInstance;
    }

    public DaoSession getSession(){
        return mSession;
    }

    public SQLiteDatabase getDatabase(){
        return mDb;
    }

    public DaoSession getNewSession(){
        return mDaoMaster.newSession();
    }

    class MyOpenHelper extends DaoMaster.OpenHelper {
        public MyOpenHelper(Context context, String name) {
            super(context, name);
        }

        public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onCreate(Database db) {
            super.onCreate(db);
        }


        @Override
        public void onUpgrade(Database db, int oldVersion, int newVersion) {
//            if (oldVersion < 103) {
                MigrationHelper.getInstance().migrate(db,
                        SiteSourceBeanDao.class,
                        CollectionMediaBeanDao.class,
                        MediaRecordBeanDao.class,
                        DownloadTaskBeanDao.class
//                    SiteSourceCategoryBeanDao.class
                );
//            }

        }
    }
}
